# record_page.py
import tkinter as tk
from tkinter import ttk, messagebox
from categories import EXPENSE_CATEGORIES, INCOME_CATEGORIES
from .base import UIBase

class RecordPage(UIBase):
    def __init__(self, parent, db, analysis=None):
        super().__init__(parent, db, analysis)
        self.parent = parent
        self.frame = ttk.Frame(parent)
        self.create_record_tab()
        
    def create_record_tab(self):
        """创建记账标签页"""
        # 交易类型选择
        type_frame = ttk.LabelFrame(self.frame, text="交易类型", padding=10)
        type_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.transaction_type = tk.StringVar(value="expense")
        ttk.Radiobutton(type_frame, text="支出", variable=self.transaction_type, 
                       value="expense", command=self.update_categories).pack(side=tk.LEFT)
        ttk.Radiobutton(type_frame, text="收入", variable=self.transaction_type, 
                       value="income", command=self.update_categories).pack(side=tk.LEFT)
        
        # 金额输入
        amount_frame = ttk.LabelFrame(self.frame, text="金额", padding=10)
        amount_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.amount_var = tk.StringVar()
        # 添加金额输入验证
        vcmd = (self.frame.register(self.validate_amount), '%P')
        amount_entry = ttk.Entry(amount_frame, textvariable=self.amount_var, font=("Arial", 14), validate='key', validatecommand=vcmd)
        amount_entry.pack(fill=tk.X)
        # 默认聚焦到金额输入框
        amount_entry.focus_set()
        
        # 分类选择 - 三级分类
        category_frame = ttk.LabelFrame(self.frame, text="分类", padding=10)
        category_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 大类选择
        main_cat_frame = ttk.Frame(category_frame)
        main_cat_frame.pack(fill=tk.X, pady=5)
        ttk.Label(main_cat_frame, text="大类:").pack(side=tk.LEFT)
        
        self.main_category_var = tk.StringVar()
        self.main_category_combo = ttk.Combobox(main_cat_frame, textvariable=self.main_category_var, state="readonly")
        self.main_category_combo.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.main_category_combo.bind('<<ComboboxSelected>>', self.update_middle_categories)
        
        # 中类选择
        middle_cat_frame = ttk.Frame(category_frame)
        middle_cat_frame.pack(fill=tk.X, pady=5)
        ttk.Label(middle_cat_frame, text="中类:").pack(side=tk.LEFT)
        
        self.middle_category_var = tk.StringVar()
        self.middle_category_combo = ttk.Combobox(middle_cat_frame, textvariable=self.middle_category_var, state="readonly")
        self.middle_category_combo.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.middle_category_combo.bind('<<ComboboxSelected>>', self.update_sub_categories)
        
        # 小类选择
        sub_cat_frame = ttk.Frame(category_frame)
        sub_cat_frame.pack(fill=tk.X, pady=5)
        ttk.Label(sub_cat_frame, text="小类:").pack(side=tk.LEFT)
        
        self.sub_category_var = tk.StringVar()
        self.sub_category_combo = ttk.Combobox(sub_cat_frame, textvariable=self.sub_category_var, state="readonly")
        self.sub_category_combo.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        
        # 具体项目
        item_frame = ttk.LabelFrame(self.frame, text="具体项目", padding=10)
        item_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.item_detail_var = tk.StringVar()
        ttk.Entry(item_frame, textvariable=self.item_detail_var).pack(fill=tk.X)
        
        # 备注
        note_frame = ttk.LabelFrame(self.frame, text="备注", padding=10)
        note_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.note_var = tk.StringVar()
        ttk.Entry(note_frame, textvariable=self.note_var).pack(fill=tk.X)
        
        # 按钮
        button_frame = ttk.Frame(self.frame)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        ttk.Button(button_frame, text="保存记录", command=self.save_transaction).pack(side=tk.RIGHT)
        ttk.Button(button_frame, text="清空", command=self.clear_form).pack(side=tk.RIGHT, padx=5)
        
        # 初始化分类
        self.update_categories()
        # 在 create_record_tab 方法末尾添加
        self.create_quick_actions()
        
    def validate_amount(self, value):
        """验证金额输入，限制为最多两位小数"""
        if value == "" or value == ".":
            return True
        try:
            # 检查是否是有效的数字
            float(value)
            # 检查小数位数
            if '.' in value:
                parts = value.split('.')
                if len(parts) > 2:  # 多个小数点
                    return False
                if len(parts[1]) > 2:  # 小数位数超过2位
                    return False
            return True
        except ValueError:
            return False

    def create_quick_actions(self):
        """创建常用分类快速选择区域"""
        quick_frame = ttk.LabelFrame(self.frame, text="常用分类快速选择", padding=10)
        quick_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 常用分类
        common_categories = [
            ("日常餐饮", "食品酒水", "餐饮", "日常餐饮"),
            ("交通出行", "交通出行", "公共交通", "交通费"),
            ("购物消费", "衣服饰品", "衣服裤子", "购物"),
            ("娱乐休闲", "休闲娱乐", "电影", "娱乐"),
            ("工资收入", "职业收入", "工资", "工资"),
            ("理财收入", "其他收入", "理财收入", "理财")
        ]
        
        for i, (name, main_cat, middle_cat, sub_cat) in enumerate(common_categories):
            # 使用默认参数解决lambda闭包问题
            btn = ttk.Button(quick_frame, text=name, 
                            command=lambda mc=main_cat, mic=middle_cat, sc=sub_cat: 
                            self.quick_select_category(mc, mic, sc))
            btn.grid(row=i//3, column=i%3, padx=5, pady=2, sticky="ew")
        
        # 配置网格权重
        for i in range(3):
            quick_frame.columnconfigure(i, weight=1)
            
    def quick_select_category(self, main_category: str, middle_category: str, sub_category: str):
        """快速选择分类"""
        # 设置交易类型
        if main_category in EXPENSE_CATEGORIES:
            self.transaction_type.set("expense")
        else:
            self.transaction_type.set("income")
            
        self.update_categories()
        
        # 设置分类
        self.main_category_var.set(main_category)
        self.update_middle_categories()
        self.middle_category_var.set(middle_category)
        self.update_sub_categories()
        self.sub_category_var.set(sub_category)
        
        # 聚焦到金额输入框
        # 获取金额输入框并设置焦点
        for child in self.frame.winfo_children():
            if isinstance(child, ttk.LabelFrame) and child.cget("text") == "金额":
                for grandchild in child.winfo_children():
                    if isinstance(grandchild, ttk.Entry):
                        grandchild.focus_set()
                        break
                break

    def update_categories(self):
        """更新分类下拉框"""
        transaction_type = self.transaction_type.get()
        categories = EXPENSE_CATEGORIES if transaction_type == "expense" else INCOME_CATEGORIES
        
        self.main_category_combo['values'] = list(categories.keys())
        if list(categories.keys()):
            self.main_category_var.set(list(categories.keys())[0])
            self.update_middle_categories()
    
    def update_middle_categories(self, event=None):
        """更新中类下拉框"""
        transaction_type = self.transaction_type.get()
        categories = EXPENSE_CATEGORIES if transaction_type == "expense" else INCOME_CATEGORIES
        
        main_category = self.main_category_var.get()
        if main_category in categories:
            middle_categories = list(categories[main_category].keys())
            self.middle_category_combo['values'] = middle_categories
            if middle_categories:
                self.middle_category_var.set(middle_categories[0])
                self.update_sub_categories()
    
    def update_sub_categories(self, event=None):
        """更新小类下拉框"""
        transaction_type = self.transaction_type.get()
        categories = EXPENSE_CATEGORIES if transaction_type == "expense" else INCOME_CATEGORIES
        
        main_category = self.main_category_var.get()
        middle_category = self.middle_category_var.get()
        
        if main_category in categories and middle_category in categories[main_category]:
            sub_categories = categories[main_category][middle_category]
            self.sub_category_combo['values'] = sub_categories
            if sub_categories:
                self.sub_category_var.set(sub_categories[0])
    
    def save_transaction(self):
        """保存交易记录"""
        try:
            amount_str = self.amount_var.get()
            if not amount_str:
                messagebox.showerror("错误", "请输入金额")
                return
                
            amount = float(amount_str)
            if amount <= 0:
                messagebox.showerror("错误", "金额必须大于0")
                return
            
            # 保留两位小数
            amount = round(amount, 2)
            
            transaction_type = self.transaction_type.get()
            main_category = self.main_category_var.get()
            middle_category = self.middle_category_var.get()
            sub_category = self.sub_category_var.get()
            item_detail = self.item_detail_var.get()
            note = self.note_var.get()
            
            if not main_category or not middle_category or not sub_category:
                messagebox.showerror("错误", "请选择完整的分类")
                return
            
            # 组合中类和小类作为sub_category存储
            full_sub_category = f"{middle_category} - {sub_category}"
            
            self.db.add_transaction(transaction_type, amount, main_category, full_sub_category, item_detail, note)
            messagebox.showinfo("成功", "记录保存成功！")
            self.clear_form()
            
            # 如果有父组件有刷新方法，则调用它
            if hasattr(self.parent, 'refresh_view_page'):
                self.parent.refresh_view_page()
            
        except ValueError:
            messagebox.showerror("错误", "请输入有效的金额")
        except Exception as e:
            messagebox.showerror("错误", f"保存失败: {str(e)}")
    
    def clear_form(self):
        """清空表单"""
        self.amount_var.set("")
        self.item_detail_var.set("")
        self.note_var.set("")
        # 聚焦到金额输入框
        for child in self.frame.winfo_children():
            if isinstance(child, ttk.LabelFrame) and child.cget("text") == "金额":
                for grandchild in child.winfo_children():
                    if isinstance(grandchild, ttk.Entry):
                        grandchild.focus_set()
                        break
                break